<?php
/**
 * URL处理
 *
 * Created		: 2011-06-14
 * Modified		: 2011-07-06
 * @link		: http://www.qixbo.com
 * @copyright	: [Qixbo.Com] (c) 2011
 * @version	: 0.2.0
 * @author		: Joseph Chen (jsph.chen@gmail.com)
 * @see			: http://blog.xe28.tk/archives/188/
 */
class Url
{
	public static $urlPattern = '~(https?://[\w\./\?\#\=\&\-\%\;]+)~';

	/**
	 * 判断字符串中是否包含有URL链接
	 * @param string $str
	 */
	public static function containUrl($str)
	{
		return preg_match(self::$urlPattern, $str);
	}

	/**
	 * 获取字符串中的URL链接
	 * @param string $str
	 */
	public static function getUrlsFromStr($str)
	{
		preg_match_all(self::$urlPattern, $str, $matches);
		if (!empty($matches[1])) {
			return $matches[1];
		} else {
			return false;
		}
	}

	/**
	 * CURL方式获取网页内容
	 * @param string $url
	 * @param int $timeout
	 */
	public static function getContents($url, $timeout=10)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
		// 修正301/302跳转取不到网页内容的问题
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		//		curl_setopt($ch, CURLOPT_HEADER, true);
		$content = curl_exec($ch);
		curl_close($ch);
		return $content;
	}

	/**
	 * 自动给URL加上链接
	 * @param string $str
	 */
	public static function addLink($str)
	{
		return preg_replace(self::$urlPattern, '<a href="$1" target="_blank">$1</a>', $str);
	}

	/**
	 * 自动给URL加上链接
	 * @param string $str
	 */
	public static function toLinkText($str)
	{
		$replace = '<a href="$1" target="_blank">'.$GLOBALS['link_text'].'</a>';
		return preg_replace(self::$urlPattern, $replace, $str);
	}

	/**
	 * 特殊加密url,防止地址被解析不完全
	 *
	 * @param string $class
	 * @return string
	 * @author
	 */
	public static function iurlencode($key)
	{
		if(preg_match('/^apache/i', $_SERVER['SERVER_SOFTWARE']))
		{
			//Apache在重写情况下 “/” 需要加密两次，否则Url rewrite出错
			return rawurlencode(str_replace(array('/', '?', '&', '#'), array( Core_Config::get('seo', 'basic', 0) ? '%252F' : '%2F', '%3F', '%26', '%23'), $key));
		} else {
			return rawurlencode(str_replace(array('/', '?', '&', '#'), array('%2F', '%3F', '%26', '%23'), $key));
		}
	}

	/**
	 * 特殊url解密,防止地址不是原地址
	 *
	 * @param string $class
	 * @return string
	 * @author icehu
	 */
	public static function iurldecode($key)
	{
		$key = rawurldecode($key);
		if(preg_match('/^apache/i', $_SERVER['SERVER_SOFTWARE']))
		{
			//Apache 会自动解码一次
			return str_replace(array('%2F') , array('/') , $key);
		} else {
			return str_replace(array('%2F', '%3F', '%26', '%23'), array('/', '?', '&', '#'), $key);
		}
	}

}
